<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名">
                <a-input v-model="queryParam.username" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="用户账户">
                <a-input v-model="queryParam.userAccount" placeholder=""/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="性别">
                  <a-select v-model="queryParam.gender" placeholder="">
                    <a-select-option :value="1">男</a-select-option>
                    <a-select-option :value="0">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="电话">
                  <a-input v-model="queryParam.phone" placeholder=""/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="邮件">
                  <a-input v-model="queryParam.email" placeholder=""/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select v-model="queryParam.userStatus" placeholder="">
                    <a-select-option :value="0">有效</a-select-option>
                    <a-select-option :value="1">无效</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="角色">
                  <!--用户角色 0 - 普通用户 1 - 管理员-->
                  <a-select v-model="queryParam.userRole" placeholder="">
                    <a-select-option :value="0">普通用户</a-select-option>
                    <a-select-option :value="1">管理员</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay" @click="menuClick">
            <a-menu-item key="1">
              <a-icon type="delete"/>
              删除
            </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作
            <a-icon type="down"/>
          </a-button>
        </a-dropdown>
      </div>

      <s-table
              ref="table"
              size="default"
              :rowKey="(record) => record.id"
              :columns="columns"
              :data="loadData"
              :alert="true"
              :rowSelection="rowSelection"
              :showPagination="true"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter"/>
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="avatar" slot-scope="text">
          <img :src="text" :alt="text" width="50px"/>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleUpd(record)">修改</a>
            <a-divider type="vertical"/>
            <a-popconfirm
                    title="确定要删除?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="handleDel(record)"
            >
            <a :disabled="record.userAccount === 'admin'">删除</a>
          </a-popconfirm>
          </template>
        </span>
      </s-table>

      <create-form
              ref="createModal"
              :visible="visible"
              :loading="confirmLoading"
              :model="mdl"
              @cancel="handleCancel"
              @ok="handleOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
  import moment from 'moment'
  import {STable, Ellipsis} from '@/components'
  import {search, add, edit, del} from '@/api/user'
  import {delete1, delete2, delete3} from '@/api/mock'

  import StepByStepModal from '@/views/list/modules/StepByStepModal'
  import CreateForm from './FormAdd'
  import pick from "lodash.pick";

  const columns = [
    {
      title: '#',
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      copyable: true,
    },
    {
      title: '用户账户',
      dataIndex: 'userAccount',
      copyable: true
    },
    {
      title: '头像',
      dataIndex: 'avatarUrl',
      scopedSlots: { customRender: 'avatar' }
    },
    {
      title: '性别',
      dataIndex: 'gender',
      customRender: (text) => text === null ? '' : text === 1 ? '男' : '女'
    },
    {
      title: '电话',
      dataIndex: 'phone',
      copyable: true
    },
    {
      title: '邮件',
      dataIndex: 'email',
      copyable: true
    },
    {
      title: '状态',
      dataIndex: 'userStatus',
      customRender: (text) => text === 0 ? '有效' : '无效'
    },
    {
      title: '星球编号',
      dataIndex: 'planetCode'
    },
    {
      title: '角色',
      dataIndex: 'userRole',
      customRender: (text) => text === 1 ? '管理员' : '普通用户'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '150px',
      scopedSlots: { customRender: 'action' },
    }
  ]

  const statusMap = {
    0: {
      status: 'default',
      text: '关闭'
    },
    1: {
      status: 'processing',
      text: '运行中'
    },
    2: {
      status: 'success',
      text: '已上线'
    },
    3: {
      status: 'error',
      text: '异常'
    }
  }

  // 表单字段
  const fields = ['id', 'username', 'userAccount', 'gender', 'phone', 'email', 'userRole', 'planetCode', 'userStatus']

  export default {
    name: 'TableList',
    components: {
      STable,
      Ellipsis,
      CreateForm,
      StepByStepModal
    },
    data() {
      this.columns = columns
      return {
        // create model
        visible: false,
        confirmLoading: false,
        mdl: null,
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          /*
            https://pro.antdv.com/components/s-table

            "data": [],
            "pageSize": 10,
            "pageNo": 0,
            "totalPage": 6,
            "totalCount": 57
          */
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          return search(requestParameters)
            .then(res => {
              return res.data
            })
        },
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    filters: {
      statusFilter(type) {
        return statusMap[type].text
      },
      statusTypeFilter(type) {
        return statusMap[type].status
      }
    },
    created() {
      // getRoleList({ t: new Date() })
      // mock list paramters
      // delete1([1,2,3])
      // delete2([1,2,3])
      // delete3([1,2,3])
    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
    },
    methods: {
      menuClick({ key }) {
        if (key === '1') {
          // console.log(this.rowSelection)
          del(this.rowSelection.selectedRowKeys)
            .then(res => {
              this.$notification['success']({
                message: '提示',
                description: '操作成功',
                duration: 3
              })
              // 刷新table
              this.$refs.table.refresh(true)
              this.selectedRowKeys = []
            })
        }
      },
      handleAdd() {
        this.visible = true
        this.$refs.createModal.init()
      },
      handleView(record) {
        this.visible = true
        this.$refs.createModal.init(record)
      },
      handleOk() {
        const form = this.$refs.createModal.form
        this.confirmLoading = true
        form.validateFields((errors, values) => {
          console.log('values', values, errors)
          if (!errors) {
            if (values.id > 0) {
              // 修改 e.g.
              edit(values).then(res => {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()

                this.$notification['success']({
                  message: '提示',
                  description: '修改成功',
                  duration: 3
                })
              })
                .catch(err => {
                  this.confirmLoading = false
                })
            } else {
              // 新增
              add(values).then(res => {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()
                this.$notification['success']({
                  message: '提示',
                  description: '新增成功，默认密码admin123',
                  duration: 3
                })
              })
                .catch(err => {
                  this.confirmLoading = false
                })
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel() {
        this.visible = false

        const form = this.$refs.createModal.form
        form.resetFields() // 清理表单数据（可不做）
      },
      handleDel(record) {
        del([record.id])
          .then(res => {
            this.$notification['success']({
              message: '提示',
              description: '操作成功',
              duration: 3
            })
            this.$refs.table.refresh(true)
          })
      },
      handleUpd(record) {
        // console.log(record)
        this.visible = true
        this.$refs.createModal.init(record)
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      resetSearchForm() {
        this.queryParam = {
          date: moment(new Date())
        }
      }
    }
  }
</script>
